<template>
  <div>
    <el-container id="message-customer-list">
      <el-main>
        <el-container>
          <el-header class="header" style="padding: 0">
            <el-form :inline="true">
              <el-form-item label="" prop="keyword">
                <el-date-picker
                  v-model="value4"
                  type="datetimerange"
                  :picker-options="pickerOptions2"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  align="right">
                </el-date-picker>
              </el-form-item>
              <el-form-item>
                <el-button @click="search" type="primary">查询</el-button>
              </el-form-item>
            </el-form>
          </el-header>
        </el-container>
        <el-table
          :data="tableData"
          border
          style="width: 100%">
          <el-table-column
            prop="nick_name"
            label="公众号">
          </el-table-column>
          <el-table-column
            prop="push_name"
            label="名称">
          </el-table-column>
          <el-table-column
            prop=""
            label="推送时间">
            <template slot-scope="scope">
              {{ formatTime(scope.row.push_time)}}
            </template>
          </el-table-column>
          <el-table-column
            prop=""
            label="推送范围">
            <template slot-scope="scope">
              {{ scope.row.push_type === 'DESIGNATED_OPEN_ID' ? '指定openids' : '48库'}}
            </template>
          </el-table-column>
          <el-table-column
            prop="finish_time"
            label="完成时间"
            width="160">
            <template slot-scope="scope">
              {{formatFinishTime(scope.row.finish_time)}}
            </template>
          </el-table-column>
          <el-table-column
            prop=""
            label="数量">
            <template slot-scope="scope">
              {{ scope.row.actual_number + '/' + scope.row.estimated_number }}
            </template>
          </el-table-column>
          <el-table-column
            prop=""
            label="创建人">
            <template slot-scope="scope">
              {{ scope.row.nickname || scope.row.username || '' }}
            </template>
          </el-table-column>
          <el-table-column
            prop=""
            label="推送状态">
            <template slot-scope="scope">
              {{getMessageStatus(scope.row.push_status)}}
            </template>
          </el-table-column>
        </el-table>
        <div class="page">
          <el-pagination
            background
            @size-change="handlePageSizeChange"
            @current-change="handleCurrentPageChange"
            :current-page="page.page + 1"
            :page-sizes="[10, 20, 100, 300, 400]"
            :page-size="20"
            layout="total, sizes, prev, pager, next, jumper"
            :total="page.totalElement">
          </el-pagination>
        </div>
      </el-main>
    </el-container>
    <el-container>
      <div class="line" style="margin-top: 80px;"></div>
    </el-container>
    <el-container>
      <div id="main" :style="{width: '100%', height: '300px'}"></div>
    </el-container>
    <el-container>
      <div class="line"></div>
    </el-container>
    <el-container>
      <div id="main1" :style="{width: '100%', height: '350px'}"></div>
    </el-container>
  </div>
</template>

<script>
  /* eslint-disable no-mixed-operators,max-len */

  import moment from 'moment';
  // import op from 'object-path';
  // import axios from 'axios';
  import { mapState, mapActions } from 'vuex';
  import echart from 'echarts';
  import service from '../../../service/count';

  import CONSTANT from '../../../constant/common';
  import cookie from '../../../lib/cookie';
  // import auth from '../../../util/auth';
  // const audioTemplate = '<audio controls><source src="{{$}}"></source></audio>';
  export default {
    data() {
      return {
        userRole: cookie(CONSTANT.COOKIE_USER_ROLE),
        value4: '',
        pickerOptions2: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            },
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            },
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            },
          }],
        },
      };
    },
    components: {
    },
    computed: {
      ...mapState({
        tableData: state => state.count.countTableList,
        page: state => state.count.countPage,
      }),
      appId() {
        const localWoa = localStorage.getItem(CONSTANT.STORAGE_LOCAL_WOA) ?
          JSON.parse(localStorage.getItem(CONSTANT.STORAGE_LOCAL_WOA)) : {};
        console.log('get local woa ', localWoa);
        return this.$store.state.woa.currentWoa.appId || localWoa.appId;
      },
      fromtime() {
        return this.value4 ? new Date(this.value4[0]).getTime() : '';
      },
      totime() {
        return this.value4 ? new Date(this.value4[1]).getTime() : '';
      },
    },
    mounted() {
      this.checkAppIdOk({
        appId: this.appId,
      }).then(() => {
        this.getCountTableList({ ...this.page, appid: this.appId });
        console.log(999);
      }, () => {
        this.$message.warning('当前公众号暂不可用，请稍后再试或选择其他公众号');
        this.$router.replace('/home');
      });
      this.lineInit();
      this.pieInit();
    },
    methods: {
      ...mapActions([
        'checkAppIdOk',
        'getCountTableList',
      ]),
      search() {
        this.getCountTableList({
          ...this.page,
          appid: this.appId,
          fromTime: this.fromtime,
          toTime: this.totime,
        });
        const dataObj = { fromTime: this.fromtime, toTime: this.totime };
        this.lineInit(dataObj);
        this.pieInit(dataObj);
      },
      formatTime(stamp) {
        return stamp ? moment(stamp).format('YYYY-MM-DD HH:mm:ss') : '立即推送';
      },
      formatFinishTime(stamp) {
        return stamp ? moment(stamp).format('YYYY-MM-DD HH:mm:ss') : '--';
      },
      getMessageStatus(status) {
        if (status === 'WAITING') {
          return '待办';
        }
        if (status === 'FAIL') {
          return '失败';
        }
        if (status === 'PUSHING') {
          return '推送中';
        }
        if (status === 'COMPLETE') {
          return '已完成';
        }
        if (status === 'INVALID') {
          return '失败';
        }
        return '未知状态';
      },
      handlePageSizeChange(val) {
        this.getCountTableList({
          ...this.page, size: val, appid: this.appId, fromTime: this.fromtime, toTime: this.totime,
        });
      },
      handleCurrentPageChange(val) {
        this.getCountTableList({
          ...this.page, page: (val - 1), appid: this.appId, fromTime: this.fromtime, toTime: this.totime,
        });
      },
      lineInit(data) {
        const that = this;
        that.lineTime = [];
        that.lineNum = [];
        const myChart = echart.init(document.getElementById('main'), 'light');
        service.getCountLine(data).then((res) => {
          res.map((item) => {
            that.lineTime.push(item.push_date);
            that.lineNum.push(item.push_num);
            return true;
          });
          myChart.setOption({
            title: {
              text: '推送人数',
              x: 'left',
            },
            tooltip: {},
            xAxis: {
              type: 'category',
              data: that.lineTime,
              name: '时间',
            },
            yAxis: {
              type: 'value',
              name: '总人数',
            },
            series: [{
              name: '人数',
              type: 'line',
              data: that.lineNum,
            }],
          });
        });
      },
      pieInit(data) {
        const that = this;
        that.pieValur = [];
        that.pieName = [];
        that.pieShow = {};
        const myChart1 = echart.init(document.getElementById('main1'), 'light');
        service.getCountPie(data)
          .then((res) => {
            that.pieValur = res;
            res.map((item, index) => {
              if (index < 5) {
                that.pieShow[item.public_address] = true;
              } else {
                that.pieShow[item.public_address] = false;
              }
              that.pieValur.push({
                name: item.public_address,
                value: item.push_num,
              });
              that.pieName.push(item.public_address);
              return true;
            });
            myChart1.setOption({
              title: {
                text: '公众号推送人数比例',
                // subtext: '纯属虚构',
                x: 'left',
              },
              tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b} : {c} ({d}%)',
              },
              legend: {
                type: 'scroll',
                orient: 'vertical',
                right: 10,
                top: 20,
                bottom: 20,
                data: that.pieName,
                selected: that.pieShow,
              },
              series: [
                {
                  name: '公众号',
                  type: 'pie',
                  radius: '55%',
                  center: ['40%', '50%'],
                  data: that.pieValur,
                  itemStyle: {
                    emphasis: {
                      shadowBlur: 10,
                      shadowOffsetX: 0,
                      shadowColor: 'rgba(0, 0, 0, 0.5)',
                    },
                  },
                },
              ],
            });
          });
      },
    },
  };
</script>

<style lang="less">
  #message-customer-list {
    font-family: Helvetica, sans-serif;
    width: 100%;
    height: 100%;
    position: relative;
    .header {
      display: flex;
      justify-content: space-between;
      .breadcrumb {
        height: 40px;
      }
    }
    .page {
      position: absolute;
      bottom: -20px;
      right: 20px;
    }
  }
  .el-message-box__content {
    max-height: 600px;
    overflow: auto;
  }
  .line{
    height: 1px;
    width: 100%;
    margin: 30px auto;
    background: #ccc;
  }
</style>
